<template>
  <div class="intelligent-mail-search-container">
    <!-- 顶部栏与侧边栏将由MainHeader和SideMenu组件提供 -->
    <MainHeader />
    
    <div class="main-container">
      <!-- 左侧导航 -->
      <SideMenu />
      
      <!-- 主内容区域 -->
      <div class="content-container">
        <div class="search-content">
          <div class="page-header">
            <div class="title">{{ t('intelligent.mail.title') }}</div>
            <div class="description">
              {{ t('intelligent.mail.description') }}
            </div>
          </div>
          
          <!-- 搜索方式切换 -->
          <div class="search-actions">
            <el-button :type="searchType === 'email' ? 'primary' : 'default'" class="action-button" @click="searchType = 'email'">
              <el-icon :size="18"><Message /></el-icon>
              {{ t('intelligent.mail.search.email') }}
            </el-button>
            <el-button :type="searchType === 'phone' ? 'primary' : 'default'" class="action-button" @click="searchType = 'phone'">
              <el-icon :size="18"><Phone /></el-icon>
              {{ t('intelligent.mail.search.phone') }}
            </el-button>
          </div>
          
          <!-- 搜索框区域 -->
          <div class="search-box">
            <el-input
              v-model="searchKeyword"
              :placeholder="t('intelligent.mail.search.placeholder')"
              class="search-input"
              clearable
              @keyup.enter="handleSearch"
            >
              <template #prefix>
                <el-icon :size="18"><Search /></el-icon>
              </template>
            </el-input>
            
            <el-button type="primary" class="search-button" @click="handleSearch">{{ t('intelligent.mail.search.button') }}</el-button>
            <el-button type="success" class="action-button batch-search-btn" @click="showBatchDialog = true">
              <el-icon :size="18"><Upload /></el-icon>
              {{ getCurrentLanguage() === 'zh' ? '批量搜索' : 'Batch Search' }}
            </el-button>
          </div>
          
          <!-- API错误信息 -->
          <div v-if="apiError" class="api-error-alert">
            <el-alert
              type="error"
              :description="`请求失败: ${apiError}。`"
              show-icon
              closable
            />
          </div>
          
          <!-- 功能介绍卡片 -->
          <div class="feature-cards" v-if="!searchResults.length && !searched">
            <div class="feature-card">
              <div class="icon">
                <el-icon :size="36" class="blue-icon"><Search /></el-icon>
              </div>
              <div class="card-content">
                <div class="card-title">{{ t('intelligent.mail.feature.keyword') }}</div>
                <div class="card-desc">{{ t('intelligent.mail.feature.keyword.desc') }}</div>
              </div>
            </div>
            
            <div class="feature-card">
              <div class="icon">
                <el-icon :size="36" class="green-icon"><Monitor /></el-icon>
              </div>
              <div class="card-content">
                <div class="card-title">{{ t('intelligent.mail.feature.collection') }}</div>
                <div class="card-desc">{{ t('intelligent.mail.feature.collection.desc') }}</div>
              </div>
            </div>
            
            <div class="feature-card">
              <div class="icon">
                <el-icon :size="36" class="purple-icon"><DataAnalysis /></el-icon>
              </div>
              <div class="card-content">
                <div class="card-title">{{ t('intelligent.mail.feature.summary') }}</div>
                <div class="card-desc">{{ t('intelligent.mail.feature.summary.desc') }}</div>
              </div>
            </div>
            
            <div class="feature-card">
              <div class="icon">
                <el-icon :size="36" class="orange-icon"><Document /></el-icon>
              </div>
              <div class="card-content">
                <div class="card-title">{{ t('intelligent.mail.feature.copy') }}</div>
                <div class="card-desc">{{ t('intelligent.mail.feature.copy.desc') }}</div>
              </div>
            </div>
          </div>
          
          <!-- 搜索结果区域 -->
          <div class="search-results" v-if="searchResults.length">
            <div class="results-header">
              <h3>{{ t('intelligent.mail.results') }} ({{ searchResults.length }}/{{ totalResults }})</h3>
              <el-button size="small" @click="clearResults">{{ t('intelligent.mail.return') }}</el-button>
            </div>
            
            <div class="result-cards">
              <div v-for="(result, index) in searchResults" :key="index" class="result-card">
                <div class="result-header">
                  <h4>{{ result.name || result.full_name || result.company_name || (result.first_name && result.last_name ? `${result.first_name} ${result.last_name}` : '') || t('intelligent.mail.unknown') }}</h4>
                  <div class="result-source" :class="getSourceClass(result.source)">{{ getSourceName(result.source) }}</div>
                </div>
                
                <div class="result-content">
                  <div class="info-row" v-if="result.company_name">
                    <span class="info-label">{{ t('intelligent.mail.company') }}:</span>
                    <span class="info-value">{{ result.company_name }}</span>
                  </div>
                  
                  <div class="info-row" v-if="result.name || result.full_name || (result.first_name && result.last_name)">
                    <span class="info-label">{{ t('intelligent.mail.contact') }}:</span>
                    <span class="info-value">{{ result.name || result.full_name || `${result.first_name || ''} ${result.middle_name ? result.middle_name + ' ' : ''}${result.last_name || ''}` }}</span>
                  </div>
                  
                  <div class="info-row" v-if="result.title || result.job_title">
                    <span class="info-label">{{ t('intelligent.mail.position') }}:</span>
                    <span class="info-value">{{ result.title || result.job_title }}</span>
                  </div>
                  
                  <div class="info-row" v-if="searchType === 'email' && (result.email || result.emails)">
                    <span class="info-label">{{ t('intelligent.mail.email') }}:</span>
                    <span class="info-value highlight">{{ result.email || result.emails }}</span>
                    <el-button size="small" @click="copyToClipboard(result.email || result.emails)" class="copy-btn">{{ t('intelligent.mail.copy') }}</el-button>
                  </div>
                  
                  <div class="info-row" v-if="searchType === 'phone' && (result.phone || result.phone_numbers)">
                    <span class="info-label">{{ t('intelligent.mail.phone') }}:</span>
                    <span class="info-value highlight">{{ result.phone || result.phone_numbers }}</span>
                    <el-button size="small" @click="copyToClipboard(result.phone || result.phone_numbers)" class="copy-btn">{{ t('intelligent.mail.copy') }}</el-button>
                  </div>
                  
                  <div class="info-row" v-if="result.location || result.locality || result.country">
                    <span class="info-label">{{ t('intelligent.mail.region') }}:</span>
                    <span class="info-value">{{ result.location || result.locality || result.country || t('intelligent.mail.unknown') }}</span>
                  </div>
                  
                  <div class="info-row" v-if="result.website || result.web_address || result.company_website">
                    <span class="info-label">{{ t('intelligent.mail.website') }}:</span>
                    <span class="info-value">
                      <a :href="formatUrl(result.website || result.web_address || result.company_website)" target="_blank">
                        {{ result.website || result.web_address || result.company_website }}
                      </a>
                    </span>
                  </div>
                  
                  <div class="info-row" v-if="result.industry || result.company_industry">
                    <span class="info-label">{{ t('intelligent.mail.industry') }}:</span>
                    <span class="info-value">{{ result.industry || result.company_industry }}</span>
                  </div>
                  
                  <div class="info-row" v-if="result.session_info">
                    <span class="info-label">{{ t('intelligent.mail.session') }}:</span>
                    <span class="info-value">{{ result.session_info }}</span>
                  </div>
                  
                  <div class="info-row" v-if="result.booth_no">
                    <span class="info-label">{{ t('intelligent.mail.booth') }}:</span>
                    <span class="info-value">{{ result.booth_no }}</span>
                  </div>
                  
                  <div class="info-row" v-if="result.screen_name">
                    <span class="info-label">{{ t('intelligent.mail.account') }}:</span>
                    <span class="info-value">{{ result.screen_name }}</span>
                  </div>
                </div>
              </div>
            </div>
            
            <!-- 加载更多按钮 -->
            <div class="load-more" v-if="searchResults.length < totalResults">
              <el-button type="primary" plain @click="loadMore" :loading="loading">{{ t('intelligent.mail.load.more') }}</el-button>
            </div>
          </div>
          
          <!-- 无搜索结果 -->
          <div class="no-results" v-if="searched && !searchResults.length && !apiError">
            <el-empty :description="t('intelligent.mail.no.results')"></el-empty>
          </div>
          
          <!-- 加载状态 -->
          <div class="loading-container" v-if="loading">
            <el-skeleton :rows="5" animated />
          </div>
        </div>
      </div>
    </div>
    
    <!-- 批量搜索对话框 -->
    <el-dialog
      v-model="showBatchDialog"
      :title="getCurrentLanguage() === 'zh' ? '批量智能搜索' : 'Batch Intelligent Search'"
      width="600px"
      :close-on-click-modal="false"
    >
      <div class="batch-dialog-content">
        <!-- 说明信息 -->
        <el-alert
          :title="getCurrentLanguage() === 'zh' ? '使用说明' : 'Instructions'"
          type="info"
          :closable="false"
          style="margin-bottom: 20px;"
        >
          <template #default>
            <div v-if="getCurrentLanguage() === 'zh'">
              <p>1. 请上传包含以下列的Excel文件：CompanyName（公司名）、FullName（姓名）、Website（网址）</p>
              <p>2. 系统将在6个数据源中搜索匹配数据：Facebook、Twitter、LinkedIn、全球企业库、广交会采购商、广交会展商</p>
              <p>3. 搜索结果将自动下载为Excel文件，每个数据源对应一个工作表</p>
              <p>4. 选择匹配类型：带手机号（匹配包含电话的数据）或 带邮箱（匹配包含邮箱的数据）</p>
            </div>
            <div v-else>
              <p>1. Please upload an Excel file with columns: CompanyName, FullName, Website</p>
              <p>2. The system will search 6 data sources: Facebook, Twitter, LinkedIn, Global Enterprise, Canton Fair Buyers, Canton Fair Exhibitors</p>
              <p>3. Results will be automatically downloaded as an Excel file with separate sheets for each data source</p>
              <p>4. Select match type: With Phone (match data with phone numbers) or With Email (match data with emails)</p>
            </div>
          </template>
        </el-alert>
        
        <!-- 匹配类型选择 -->
        <div class="match-type-selector" style="margin-bottom: 20px;">
          <label style="font-weight: bold; margin-right: 10px;">
            {{ getCurrentLanguage() === 'zh' ? '匹配类型：' : 'Match Type:' }}
          </label>
          <el-radio-group v-model="batchMatchType">
            <el-radio :label="1">
              {{ getCurrentLanguage() === 'zh' ? '带手机号' : 'With Phone' }}
            </el-radio>
            <el-radio :label="2">
              {{ getCurrentLanguage() === 'zh' ? '带邮箱' : 'With Email' }}
            </el-radio>
          </el-radio-group>
        </div>
        
        <!-- 文件上传 -->
        <el-upload
          ref="uploadRef"
          class="upload-demo"
          drag
          :auto-upload="false"
          :limit="1"
          :on-change="handleFileChange"
          :on-exceed="handleExceed"
          accept=".xlsx,.xls"
          :file-list="fileList"
        >
          <el-icon class="el-icon--upload"><upload-filled /></el-icon>
          <div class="el-upload__text">
            {{ getCurrentLanguage() === 'zh' ? '将Excel文件拖到此处，或' : 'Drop Excel file here or' }}
            <em>{{ getCurrentLanguage() === 'zh' ? '点击上传' : 'click to upload' }}</em>
          </div>
          <template #tip>
            <div class="el-upload__tip">
              {{ getCurrentLanguage() === 'zh' ? '仅支持 .xlsx 和 .xls 格式的文件' : 'Only .xlsx and .xls files are supported' }}
            </div>
          </template>
        </el-upload>
        
        <!-- 进度条 -->
        <div v-if="batchUploading" style="margin-top: 20px;">
          <el-progress :percentage="uploadProgress" :status="uploadStatus"></el-progress>
          <div style="text-align: center; margin-top: 10px; color: #606266;">
            {{ uploadStatusText }}
          </div>
        </div>
      </div>
      
      <template #footer>
        <span class="dialog-footer">
          <el-button type="warning" plain @click="downloadTemplate">
            <el-icon><Download /></el-icon>
            {{ getCurrentLanguage() === 'zh' ? '下载Excel模板' : 'Excel Template' }}
          </el-button>
          <el-button @click="cancelBatchUpload">
            {{ getCurrentLanguage() === 'zh' ? '取消' : 'Cancel' }}
          </el-button>
          <el-button
            type="primary"
            @click="submitBatchSearch"
            :loading="batchUploading"
            :disabled="!selectedFile"
          >
            {{ getCurrentLanguage() === 'zh' ? '开始搜索' : 'Start Search' }}
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { Search, Message, Phone, Document, Monitor, DataAnalysis, Upload, UploadFilled, Download } from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'
import axios from 'axios'
import MainHeader from '@/components/MainHeader.vue'
import SideMenu from '@/components/SideMenu.vue'
import { useRouter } from 'vue-router'
import { t, getCurrentLanguage } from '@/utils/i18n'

// 定义响应式数据
const searchType = ref('email') // email 或 phone
const searchKeyword = ref('')
const searchResults = ref([])
const loading = ref(false)
const searched = ref(false)
const currentPage = ref(1)
const pageSize = ref(10)
const totalResults = ref(0)
const apiError = ref(null)
const router = useRouter()

// 批量搜索相关数据
const showBatchDialog = ref(false)
const batchMatchType = ref(1) // 1-带手机号, 2-带邮箱
const selectedFile = ref(null)
const fileList = ref([])
const uploadRef = ref(null)
const batchUploading = ref(false)
const uploadProgress = ref(0)
const uploadStatus = ref('')
const uploadStatusText = ref('')

// 搜索
const handleSearch = async () => {
  if (!searchKeyword.value.trim()) {
    if (getCurrentLanguage() === 'zh') {
      ElMessage.warning('请输入搜索关键词')
    } else {
      ElMessage.warning('Please enter a search keyword')
    }
    return
  }

  // 检查是否有token
  const token = localStorage.getItem('token')
  if (!token) {
    if (getCurrentLanguage() === 'zh') {
      ElMessage.warning('您尚未登录，请先登录后再进行查询')
    } else {
      ElMessage.warning('You are not logged in, please log in first to search')
    }
    // 保存当前路径用于登录后重定向
    localStorage.setItem('redirectPath', '/intelligent-mail-search')
    // 跳转到登录页
    router.push('/login')
    return
  }

  // 统计真实搜索次数
  let count = parseInt(localStorage.getItem('searchCount_intelligentMail') || '0')
  localStorage.setItem('searchCount_intelligentMail', count + 1)

  loading.value = true
  searched.value = true
  currentPage.value = 1
  apiError.value = null

  try {
    const response = await axios.get('/api/intelligent-search', {
      params: {
        keyword: searchKeyword.value,
        type: searchType.value,
        page: currentPage.value,
        size: pageSize.value
      },
      headers: {
        'Authorization': `Bearer ${token}`  // 确保请求携带token
      },
      timeout: 30000
    });

    // 检查响应状态码
    if (response.data.code !== 200) {
      apiError.value = response.data.msg || '服务器返回错误状态码';
      if (getCurrentLanguage() === 'zh') {
        ElMessage.error(`搜索失败: ${apiError.value}`);
      } else {
        ElMessage.error(`Search failed`);
      }
      searchResults.value = [];
      totalResults.value = 0;
      return;
    }

    // 检查data字段是否存在
    // if (!response.data.data) {
    //   apiError.value = '服务器返回的数据格式不正确';
    //   if (getCurrentLanguage === 'zh') {
    //     ElMessage.error('服务器返回的数据格式不正确');
    //   } else {
    //     ElMessage.error('Server returned data format is incorrect');
    //   }
    //   searchResults.value = [];
    //   totalResults.value = 0;
    //   return;
    // }

    // 提取数据
    const responseData = response.data.data;
    searchResults.value = responseData.results || [];
    totalResults.value = parseInt(responseData.total) || 0;

    // 检查是否有结果
    if (searchResults.value.length === 0) {
      if (getCurrentLanguage() === 'zh') {
        ElMessage.info('没有找到匹配的结果');
      } else {
        ElMessage.info('No matching results found');
      }
    } else {
      if (getCurrentLanguage() === 'zh') {
        ElMessage.success(`找到 ${totalResults.value} 条结果`);
      } else {
        ElMessage.success(`Found ${totalResults.value} results`);
      }
    }

  } catch (error) {

    // 详细的错误处理
    if (error.response) {
      // 服务器返回了错误状态码
      const status = error.response.status;

      // 尝试获取后端返回的错误信息
      const backendMsg = error.response.data?.msg ||
          error.response.data?.error ||
          error.response.data?.message;

      if (backendMsg) {
        apiError.value = `服务器返回错误(${status}): ${backendMsg}`;
      } else {
        apiError.value = `服务器返回错误(${status}): ${error.message || '未知错误'}`;
      }
    } else if (error.request) {
      // 请求已发出，但没有收到响应
      apiError.value = '服务器未响应，请检查后端服务是否正常运行';
    } else {
      // 请求设置触发的错误
      apiError.value = `请求错误: ${error.message}`;
    }
    if (getCurrentLanguage() === 'zh') {
      ElMessage.error(`搜索失败: ${apiError.value}`);
    } else {
      ElMessage.error(`Search failed`);
    }
    searchResults.value = [];
    totalResults.value = 0;
  } finally {
    loading.value = false;
  }
};

// 加载更多结果
const loadMore = async () => {
  if (searchResults.value.length >= totalResults.value) {
    if (getCurrentLanguage() === 'zh') {
      ElMessage.info('已加载全部数据');
    } else {
      ElMessage.info('All data has been loaded');
    }
    return;
  }

  // 获取token
  const token = localStorage.getItem('token')
  if (!token) {
    if (getCurrentLanguage() === 'zh') {
      ElMessage.warning('您的登录已过期，请重新登录')
    } else {
      ElMessage.warning('Your login has expired, please log in again')
    }
    router.push('/login')
    return
  }

  loading.value = true;
  currentPage.value += 1;

  try {
    const response = await axios.get('/api/intelligent-search', {
      params: {
        keyword: searchKeyword.value,
        type: searchType.value,
        page: currentPage.value,
        size: pageSize.value
      },
      headers: {
        'Authorization': `Bearer ${token}`
      }
    });

    // 检查响应状态码[1,2](@ref)
    if (response.data.code !== 200) {
      if (getCurrentLanguage() === 'zh') {
        ElMessage.error(`加载失败: ${response.data.msg || '服务器返回错误状态码'}`);
      } else {
        ElMessage.error(`Load failed`);
      }
      currentPage.value -= 1;
      return;
    }

    // 检查data字段是否存在[1](@ref)
    if (!response.data.data) {
      if (getCurrentLanguage() === 'zh') {
        ElMessage.error('服务器返回的数据格式不正确');
      } else {
        ElMessage.error('Server returned data format is incorrect');
      }
      currentPage.value -= 1;
      return;
    }

    const responseData = response.data.data;
    const newResults = responseData.results || [];

    // 更新总结果数[2,7](@ref)
    totalResults.value = parseInt(responseData.total) || 0;

    // 合并新结果[3](@ref)
    searchResults.value = [...searchResults.value, ...newResults];

    // 检查是否还有更多数据[5](@ref)
    if (newResults.length === 0) {
      if (getCurrentLanguage() === 'zh') {
        ElMessage.info('已加载全部数据');
      } else {
        ElMessage.info('All data has been loaded');
      }
    } else {
      if (getCurrentLanguage() === 'zh') {
        ElMessage.success(`成功加载 ${newResults.length} 条新数据`);
      } else {
        ElMessage.success(`Successfully loaded ${newResults.length} new data`);
      }
    }

  } catch (error) {
    currentPage.value -= 1;

    // 更详细的错误处理[1](@ref)
    if (error.response) {
      // 尝试获取后端返回的错误信息
      const backendMsg = error.response.data?.msg ||
          error.response.data?.error ||
          error.response.data?.message;

      if (backendMsg) {
        if (getCurrentLanguage() === 'zh') {
          ElMessage.error(`加载更多失败: ${backendMsg}`);
        } else {
          ElMessage.error(`Load more failed`);
        }
      } else {
        if (getCurrentLanguage() === 'zh') {
          ElMessage.error(`加载更多失败: ${error.message || '服务器连接失败'}`);
        } else {
          ElMessage.error(`Load more failed`);
        }
      }
    } else if (error.request) {
      if (getCurrentLanguage() === 'zh') {
        ElMessage.error('服务器未响应，请检查网络连接');
      } else {
        ElMessage.error('Server did not respond, please check your network connection');
      }
    } else {
      if (getCurrentLanguage() === 'zh') {
        ElMessage.error(`加载更多失败: ${error.message}`);
      } else {
        ElMessage.error(`Load more failed`);
      }
    }
  } finally {
    loading.value = false;
  }
};

// 清除搜索结果
const clearResults = () => {
  searchResults.value = [];
  searched.value = false;
  currentPage.value = 1;
  totalResults.value = 0;
  apiError.value = null;
};

// 复制到剪贴板
const copyToClipboard = (text) => {
  navigator.clipboard.writeText(text)
    .then(() => {
      if (getCurrentLanguage() === 'zh') {
        ElMessage.success('已复制到剪贴板');
      } else {
        ElMessage.success('Copied to clipboard');
      }
    })
    .catch(() => {
      if (getCurrentLanguage() === 'zh') {
        ElMessage.error('复制失败，请手动复制');
      } else {
        ElMessage.error('Copy failed, please manually copy');
      }
    });
};

// 获取数据源名称
const getSourceName = (source) => {
  const sourceMap = {
    'canton_fair_exhibitors': t('intelligent.mail.source.canton.exhibitor'),
    'canton_fair_purchasers': t('intelligent.mail.source.canton.purchaser'),
    'facebook_data': t('intelligent.mail.source.facebook'),
    'twitter_data': t('intelligent.mail.source.twitter'),
    'linkedin_data': t('intelligent.mail.source.linkedin'),
    'global_enterprise_library': t('intelligent.mail.source.enterprise')
  };
  return sourceMap[source] || t('intelligent.mail.source.unknown');
};

// 格式化URL，确保以http或https开头
const formatUrl = (url) => {
  if (!url) return '#';
  if (url.startsWith('http://') || url.startsWith('https://')) {
    return url;
  }
  return 'http://' + url;
};

// 获取数据源对应的CSS类
const getSourceClass = (source) => {
  const classMap = {
    'canton_fair_exhibitors': 'source-canton',
    'canton_fair_purchasers': 'source-canton',
    'facebook_data': 'source-facebook',
    'twitter_data': 'source-twitter',
    'linkedin_data': 'source-linkedin',
    'global_enterprise_library': 'source-company'
  };
  return classMap[source] || 'source-unknown';
};

// 批量搜索相关方法
// 文件选择变化
const handleFileChange = (file, fileListParam) => {
  selectedFile.value = file.raw;
  fileList.value = fileListParam;
};

// 文件超出限制
const handleExceed = () => {
  if (getCurrentLanguage() === 'zh') {
    ElMessage.warning('只能上传一个文件，请先移除已选文件');
  } else {
    ElMessage.warning('Only one file can be uploaded, please remove the selected file first');
  }
};

// 取消批量上传
const cancelBatchUpload = () => {
  if (batchUploading.value) {
    if (getCurrentLanguage() === 'zh') {
      ElMessage.warning('搜索正在进行中，请稍后再试');
    } else {
      ElMessage.warning('Search is in progress, please try again later');
    }
    return;
  }
  
  showBatchDialog.value = false;
  selectedFile.value = null;
  fileList.value = [];
  uploadProgress.value = 0;
  uploadStatus.value = '';
  uploadStatusText.value = '';
};

// 提交批量搜索
const submitBatchSearch = async () => {
  if (!selectedFile.value) {
    if (getCurrentLanguage() === 'zh') {
      ElMessage.warning('请先选择要上传的Excel文件');
    } else {
      ElMessage.warning('Please select an Excel file to upload first');
    }
    return;
  }

  // 检查文件格式
  const fileName = selectedFile.value.name;
  if (!fileName.endsWith('.xlsx') && !fileName.endsWith('.xls')) {
    if (getCurrentLanguage() === 'zh') {
      ElMessage.error('文件格式不正确，只支持.xlsx和.xls格式');
    } else {
      ElMessage.error('Invalid file format, only .xlsx and .xls are supported');
    }
    return;
  }

  // 检查token
  const token = localStorage.getItem('token');
  if (!token) {
    if (getCurrentLanguage() === 'zh') {
      ElMessage.warning('您尚未登录，请先登录');
    } else {
      ElMessage.warning('You are not logged in, please log in first');
    }
    router.push('/login');
    return;
  }

  // 准备FormData
  const formData = new FormData();
  formData.append('file', selectedFile.value);
  formData.append('matchType', batchMatchType.value);

  batchUploading.value = true;
  uploadProgress.value = 0;
  uploadStatus.value = '';
  
  if (getCurrentLanguage() === 'zh') {
    uploadStatusText.value = '正在上传文件...';
  } else {
    uploadStatusText.value = 'Uploading file...';
  }

  try {
    const response = await axios.post('/api/intelligent-search/batch', formData, {
      headers: {
        'Authorization': `Bearer ${token}`,
        'Content-Type': 'multipart/form-data'
      },
      responseType: 'blob', // 重要：接收二进制数据
      timeout: 900000, // 15分钟超时（批量搜索数据量大时需要更长时间）
      onUploadProgress: (progressEvent) => {
        // 上传进度
        if (progressEvent.total) {
          uploadProgress.value = Math.round((progressEvent.loaded * 50) / progressEvent.total);
        }
      },
      onDownloadProgress: (progressEvent) => {
        // 下载进度
        if (progressEvent.total) {
          const downloadProgress = Math.round((progressEvent.loaded * 50) / progressEvent.total);
          uploadProgress.value = 50 + downloadProgress;
        } else {
          uploadProgress.value = 75;
        }
        
        if (getCurrentLanguage() === 'zh') {
          uploadStatusText.value = '正在处理搜索结果...';
        } else {
          uploadStatusText.value = 'Processing search results...';
        }
      }
    });

    // 检查响应是否为错误JSON（而非Excel文件）
    if (response.data.type === 'application/json') {
      // 说明返回的是错误信息
      const reader = new FileReader();
      reader.onload = (e) => {
        try {
          const errorData = JSON.parse(e.target.result);
          if (getCurrentLanguage() === 'zh') {
            ElMessage.error(`搜索失败: ${errorData.msg || '未知错误'}`);
          } else {
            ElMessage.error('Search failed');
          }
        } catch (err) {
          if (getCurrentLanguage() === 'zh') {
            ElMessage.error('搜索失败，返回数据格式错误');
          } else {
            ElMessage.error('Search failed, invalid response format');
          }
        }
      };
      reader.readAsText(response.data);
      uploadProgress.value = 0;
      uploadStatus.value = 'exception';
      uploadStatusText.value = '';
      return;
    }

    uploadProgress.value = 100;
    uploadStatus.value = 'success';
    
    if (getCurrentLanguage() === 'zh') {
      uploadStatusText.value = '搜索完成，正在下载结果...';
    } else {
      uploadStatusText.value = 'Search completed, downloading results...';
    }

    // 创建下载链接
    const blob = new Blob([response.data], {
      type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
    });
    const url = window.URL.createObjectURL(blob);
    const link = document.createElement('a');
    link.href = url;
    
    // 从响应头获取文件名，如果没有则使用默认名称
    const contentDisposition = response.headers['content-disposition'];
    let filename = `批量搜索结果_${new Date().getTime()}.xlsx`;
    
    if (contentDisposition) {
      const filenameMatch = contentDisposition.match(/filename[^;=\n]*=((['"]).*?\2|[^;\n]*)/);
      if (filenameMatch && filenameMatch[1]) {
        filename = decodeURIComponent(filenameMatch[1].replace(/['"]/g, ''));
      }
    }
    
    link.download = filename;
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
    window.URL.revokeObjectURL(url);

    if (getCurrentLanguage() === 'zh') {
      ElMessage.success('批量搜索完成，结果已下载');
    } else {
      ElMessage.success('Batch search completed, results downloaded');
    }

    // 延迟关闭对话框
    setTimeout(() => {
      showBatchDialog.value = false;
      selectedFile.value = null;
      fileList.value = [];
      uploadProgress.value = 0;
      uploadStatus.value = '';
      uploadStatusText.value = '';
    }, 1500);

  } catch (error) {
    uploadProgress.value = 0;
    uploadStatus.value = 'exception';
    uploadStatusText.value = '';
    
    console.error('批量搜索错误:', error);
    
    if (error.response) {
      // 尝试解析blob错误消息
      if (error.response.data instanceof Blob) {
        const reader = new FileReader();
        reader.onload = (e) => {
          try {
            const errorData = JSON.parse(e.target.result);
            if (getCurrentLanguage() === 'zh') {
              ElMessage.error(`搜索失败: ${errorData.msg || '未知错误'}`);
            } else {
              ElMessage.error('Search failed');
            }
          } catch (err) {
            if (getCurrentLanguage() === 'zh') {
              ElMessage.error('搜索失败: 服务器返回错误');
            } else {
              ElMessage.error('Search failed: server returned error');
            }
          }
        };
        reader.readAsText(error.response.data);
      } else {
        const errorMsg = error.response.data?.msg || error.message;
        if (getCurrentLanguage() === 'zh') {
          ElMessage.error(`搜索失败: ${errorMsg}`);
        } else {
          ElMessage.error('Search failed');
        }
      }
    } else if (error.request) {
      if (getCurrentLanguage() === 'zh') {
        ElMessage.error('服务器未响应，请检查网络连接');
      } else {
        ElMessage.error('Server did not respond, please check network connection');
      }
    } else {
      if (getCurrentLanguage() === 'zh') {
        ElMessage.error(`请求失败: ${error.message}`);
      } else {
        ElMessage.error('Request failed');
      }
    }
  } finally {
    batchUploading.value = false;
  }
};

// 下载模板
const downloadTemplate = async () => {
  const lang = getCurrentLanguage();
  const token = localStorage.getItem('token');
  
  try {
    const response = await axios.get('/api/intelligent-search/batch/template', {
      params: { lang: lang },
      headers: {
        'Authorization': `Bearer ${token}`
      },
      responseType: 'blob'
    });
    
    const blob = new Blob([response.data], { type: 'application/vnd.ms-excel' });
    const url = window.URL.createObjectURL(blob);
    const link = document.createElement('a');
    link.href = url;
    
    const fileName = lang === 'zh' ? '智能搜邮模板.xls' : 'Intelligent_Postal_Search_Template.xls';
    link.setAttribute('download', fileName);
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
    window.URL.revokeObjectURL(url);
    
    if (lang === 'zh') {
      ElMessage.success('模板下载成功');
    } else {
      ElMessage.success('Template downloaded successfully');
    }
  } catch (error) {
    console.error('下载模板失败:', error);
    if (lang === 'zh') {
      ElMessage.error('模板下载失败，请稍后重试');
    } else {
      ElMessage.error('Template download failed, please try again later');
    }
  }
};
</script>

<style scoped>
.intelligent-mail-search-container {
  display: flex;
  flex-direction: column;
  width: 100%;
  height: 100vh;
  overflow: hidden;
}

.main-container {
  display: flex;
  flex: 1;
  height: calc(100vh - 60px);
  overflow: hidden;
}

.content-container {
  flex: 1;
  padding: 20px;
  overflow-y: auto;
  background-color: #f5f7fa;
}

.search-content {
  padding: 30px;
  background-color: #fff;
  border-radius: 8px;
  display: flex;
  flex-direction: column;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
}

.page-header {
  text-align: center;
  margin-bottom: 20px;
}

.title {
  font-size: 28px;
  font-weight: bold;
  color: #409eff;
  margin-bottom: 10px;
}

.description {
  color: #606266;
  font-size: 14px;
  max-width: 800px;
  margin: 0 auto;
}

.search-actions {
  display: flex;
  justify-content: center;
  margin-bottom: 20px;
}

.action-button {
  margin: 0 5px;
  padding: 10px 20px;
}

.action-button.active {
  background-color: #409eff;
  color: white;
}

.search-box {
  display: flex;
  justify-content: center;
  align-items: center;
  margin-bottom: 30px;
  width: 100%;
  max-width: 900px;
  margin-left: auto;
  margin-right: auto;
}

.search-input {
  flex: 1;
}

.search-button {
  width: 80px;
  margin-left: 10px;
}

.api-error-alert {
  margin-bottom: 20px;
}

.feature-cards {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 20px;
  margin-top: 20px;
}

.feature-card {
  display: flex;
  padding: 15px;
  background-color: #fff;
  border-radius: 8px;
  border: 1px solid #ebeef5;
}

.feature-card .icon {
  margin-right: 20px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.blue-icon {
  color: #409eff;
  background-color: #ecf5ff;
  padding: 10px;
  border-radius: 10px;
  font-size: 24px;
}

.green-icon {
  color: #67c23a;
  background-color: #f0f9eb;
  padding: 10px;
  border-radius: 10px;
  font-size: 24px;
}

.purple-icon {
  color: #722ed1;
  background-color: #f9f0ff;
  padding: 10px;
  border-radius: 10px;
  font-size: 24px;
}

.orange-icon {
  color: #fa8c16;
  background-color: #fff7e6;
  padding: 10px;
  border-radius: 10px;
  font-size: 24px;
}

.card-content {
  flex: 1;
}

.card-title {
  font-weight: bold;
  margin-bottom: 10px;
  font-size: 16px;
}

.card-desc {
  color: #606266;
  font-size: 14px;
  line-height: 1.5;
}

/* 搜索结果样式 */
.search-results {
  margin-top: 20px;
}

.results-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.results-header h3 {
  font-size: 18px;
  color: #303133;
  margin: 0;
}

.result-cards {
  display: flex;
  flex-direction: column;
  gap: 15px;
}

.result-card {
  border: 1px solid #dcdfe6;
  border-radius: 8px;
  padding: 15px;
  background-color: #fff;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);
  transition: all 0.3s;
}

.result-card:hover {
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
  transform: translateY(-2px);
}

.result-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 10px;
  padding-bottom: 10px;
  border-bottom: 1px solid #ebeef5;
}

.result-header h4 {
  margin: 0;
  font-size: 16px;
  color: #303133;
}

.result-source {
  font-size: 12px;
  padding: 2px 8px;
  border-radius: 10px;
  color: #fff;
}

.source-canton {
  background-color: #f56c6c;
}

.source-facebook {
  background-color: #3b5998;
}

.source-twitter {
  background-color: #1da1f2;
}

.source-linkedin {
  background-color: #0077b5;
}

.source-company {
  background-color: #67c23a;
}

.source-unknown {
  background-color: #909399;
}

.result-content {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.info-row {
  display: flex;
  align-items: center;
}

.info-label {
  min-width: 80px;
  font-weight: bold;
  color: #606266;
  font-size: 14px;
}

.info-value {
  flex: 1;
  color: #303133;
  font-size: 14px;
}

.highlight {
  color: #409eff;
  font-weight: bold;
}

.copy-btn {
  margin-left: 10px;
  padding: 4px 8px;
  font-size: 12px;
}

.load-more {
  margin-top: 20px;
  text-align: center;
}

.no-results {
  margin-top: 40px;
  text-align: center;
}

.loading-container {
  margin-top: 20px;
  padding: 20px;
}

/* 批量搜索按钮样式 */
.batch-search-btn {
  margin-left: 10px;
}

/* 批量搜索对话框样式 */
.batch-dialog-content {
  padding: 10px 0;
}

.batch-dialog-content p {
  margin: 8px 0;
  line-height: 1.6;
  font-size: 14px;
}

.match-type-selector {
  display: flex;
  align-items: center;
}

/* 上传组件样式优化 */
:deep(.el-upload-dragger) {
  padding: 40px 20px;
}

:deep(.el-icon--upload) {
  font-size: 48px;
  color: #409eff;
  margin-bottom: 16px;
}

:deep(.el-upload__text) {
  font-size: 14px;
  color: #606266;
}

:deep(.el-upload__text em) {
  color: #409eff;
  font-style: normal;
}

:deep(.el-upload__tip) {
  margin-top: 10px;
  font-size: 12px;
  color: #909399;
}
</style>
